/**
 * Copyright &copy; 2012-2017 <a href="https://vivo.com/">vivo</a> All rights reserved.
 */
package com.vivo.system.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.thinkgem.jeesite.modules.sys.entity.Dict;
import com.thinkgem.jeesite.modules.sys.entity.Role;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.utils.excel.ImportExcel;
import com.vivo.system.entity.SysRolePost;
import com.vivo.system.service.SysRolePostService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 职位角色Controller
 * @author jyangye
 * @version 2018-01-11
 */
@Controller
@RequestMapping(value = "${adminPath}/system/sysRolePost")
public class SysRolePostController extends BaseController {

	@Autowired
	private SysRolePostService sysRolePostService;

	@Autowired
    private SystemService systemService;
	
	@ModelAttribute
	public SysRolePost get(@RequestParam(required=false) String id) {
		SysRolePost entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = sysRolePostService.get(id);
		}
		if (entity == null){
			entity = new SysRolePost();
		}
		return entity;
	}
	
	@RequiresPermissions("system:sysRolePost:view")
	@RequestMapping(value = {"list", ""})
	public String list(SysRolePost sysRolePost, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<SysRolePost> page = sysRolePostService.findPage(new Page<SysRolePost>(request, response), sysRolePost); 
		model.addAttribute("page", page);
		return "vivo/system/sysRolePostList";
	}

	@RequiresPermissions("system:sysRolePost:view")
	@RequestMapping(value = "form")
	public String form(SysRolePost sysRolePost, Model model) {
		model.addAttribute("sysRolePost", sysRolePost);

        List<Role> roles = systemService.findAllRole();

        List<Dict> dictList = new ArrayList<Dict>();

        for(Role role: roles) {
            Dict dict = new Dict();
            dict.setLabel(role.getName());
            dict.setValue(role.getId());
            dictList.add(dict);
        }
        model.addAttribute("roleList", dictList);

        return "vivo/system/sysRolePostForm";
	}

	@RequiresPermissions("system:sysRolePost:edit")
	@RequestMapping(value = "save")
	public String save(SysRolePost sysRolePost, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, sysRolePost)){
			return form(sysRolePost, model);
		}
		sysRolePostService.save(sysRolePost);
		addMessage(redirectAttributes, "保存职位角色成功");
		return "redirect:"+Global.getAdminPath()+"/system/sysRolePost/?repage";
	}
	
	@RequiresPermissions("system:sysRolePost:del")
	@RequestMapping(value = "delete")
	public String delete(SysRolePost sysRolePost, RedirectAttributes redirectAttributes) {
		sysRolePostService.delete(sysRolePost);
		addMessage(redirectAttributes, "删除职位角色成功");
		return "redirect:"+Global.getAdminPath()+"/system/sysRolePost/?repage";
	}

	/**
	 * 批量删除职位角色
	 */
	@RequiresPermissions("system:sysRolePost:del")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(String ids, RedirectAttributes redirectAttributes) {
		String idArray[] =ids.split(",");
		for(String id : idArray){
			sysRolePostService.delete(sysRolePostService.get(id));
		}
		addMessage(redirectAttributes, "删除职位角色成功");
		return "redirect:"+Global.getAdminPath()+"/system/sysRolePost/?repage";
	}

	/**
	 * 导出excel文件
	 */
	@RequiresPermissions("system:sysRolePost:edit")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(SysRolePost sysRolePost, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "职位角色"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<SysRolePost> page = sysRolePostService.findPage(new Page<SysRolePost>(request, response, -1), sysRolePost);
    		new ExportExcel("职位角色", SysRolePost.class).setDataList(page.getList()).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出职位角色记录失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/sysRolePost/?repage";
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("system:sysRolePost:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<SysRolePost> list = ei.getDataList(SysRolePost.class);
			for (SysRolePost sysRolePost : list){
				try{
					sysRolePostService.save(sysRolePost);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条职位角色记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条职位角色记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入职位角色失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/sysRolePost/?repage";
    }

	/**
	 * 下载导入{functionNameSimple}数据模板
	 */
	@RequiresPermissions("system:sysRolePost:edit")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "职位角色数据导入模板.xlsx";
    		List<SysRolePost> list = Lists.newArrayList();
    		new ExportExcel("职位角色数据", SysRolePost.class, 2).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/system/sysRolePost/?repage";
    }

}